package com.bootdo.api;

import com.bootdo.common.config.BootdoConfig;
import com.bootdo.common.config.Constant;
import com.bootdo.common.controller.BaseRest;
import com.bootdo.common.domain.FileDO;
import com.bootdo.common.service.FileService;
import com.bootdo.common.utils.FileType;
import com.bootdo.common.utils.FileUtil;
import com.bootdo.common.utils.MD5Utils;
import com.bootdo.common.utils.R;
import com.bootdo.common.utils.ShiroUtils;
import com.bootdo.common.utils.StringUtils;
import com.bootdo.system.domain.UserDO;
import com.bootdo.system.domain.UserDORepository;
import com.bootdo.system.service.UserService;
import org.apache.catalina.servlet4preview.http.HttpServletRequest;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * Created by allards on 01/31/18.
 * Email: allards@synnex.com
 */
@RestController
@RequestMapping("/api/user")
@Transactional
public class UserRest extends BaseRest{
    @Autowired
    UserService userService;
    @Autowired
    private FileService sysFileService;

    @Autowired
    private BootdoConfig bootdoConfig;
    @Autowired
    UserDORepository userDORepository;

    @PostMapping(value = "/save",produces = "application/json; charset=UTF-8")
    R save(@RequestBody UserDO user) {
        if (Constant.DEMO_ACCOUNT.equals(getUsername())) {
            return R.error(1, "演示系统不允许修改,完整体验请部署程序");
        }

        UserDO userDO1=new UserDO();
        userDO1.setUsername(user.getUsername());
        List list =userDORepository.findAll(Example.of(userDO1));
        if(list!=null&&list.size()>0){
            return R.error(1, "用户已经存在");
        }

        user.setPassword(MD5Utils.encrypt(user.getUsername(), user.getPassword()));
        user.setDeptId(17l);
        List<Long> roleids=new ArrayList<>();
        roleids.add(61l);
        user.setRoleIds(roleids);
        user.setType("user");
        user.setStatus(1);
        if (userService.save(user) > 0) {
            return R.ok();
        }
        return R.error();
    }

    @PostMapping(value = "/update",produces = "application/json; charset=UTF-8")
    R update(@RequestBody UserDO user) {

        if (Constant.DEMO_ACCOUNT.equals(getUsername())) {
            return R.error(1, "演示系统不允许修改,完整体验请部署程序");
        }
        UserDO userDO1 = userDORepository.getOne(getUserId());
        if(userDO1!=null){
            if(StringUtils.isNotBlank(user.getName())){
                userDO1.setName(user.getName());
            }
            if(null!=user.getBirth()){
                userDO1.setBirth(user.getBirth());
            }
            if(StringUtils.isNotBlank(user.getCity())){
                userDO1.setCity(user.getCity());
            }
            if(StringUtils.isNotBlank(user.getDistrict())){
                userDO1.setDistrict(user.getDistrict());
            }
            if(StringUtils.isNotBlank(user.getEmail())){
                userDO1.setEmail(user.getEmail());
            }
            if(StringUtils.isNotBlank(user.getHobby())){
                userDO1.setHobby(user.getHobby());
            }
            if(StringUtils.isNotBlank(user.getLiveAddress())){
                userDO1.setLiveAddress(user.getLiveAddress());
            }
            if(StringUtils.isNotBlank(user.getMobile())){
                userDO1.setMobile(user.getMobile());
            }
            if(StringUtils.isNotBlank(user.getProvince())){
                userDO1.setProvince(user.getProvince());
            }
            if(null!=user.getSex()){
                userDO1.setSex(user.getSex());
            }
            userDORepository.saveAndFlush(userDO1);
            return R.ok();
        }else{
            return R.error();
        }
    }

    @GetMapping(value = "/userInfo",produces = "application/json; charset=UTF-8")
    UserDO userInfo() {
        UserDO userDO = userDORepository.findOne(getUserId());
        return userDO;
    }

    @PostMapping(value = "/login",produces = "application/json; charset=UTF-8")
    R ajaxLogin(String username, String password) {
        password = MD5Utils.encrypt(username, password);
        UsernamePasswordToken token = new UsernamePasswordToken(username, password);
        Subject subject = SecurityUtils.getSubject();
        try {
            subject.login(token);
            return R.ok().put("accessToken",subject.getSession().getId());
        } catch (AuthenticationException e) {
            return R.error("用户或密码错误");
        }
    }

    @GetMapping(value = "/logout",produces = "application/json; charset=UTF-8")
    String logout() {
        ShiroUtils.logout();
        return "redirect:/login";
    }

    @PostMapping(value = "/upload",produces = "application/json; charset=UTF-8")
    R upload(@RequestParam("file") MultipartFile file, HttpServletRequest request) {
        if ("test".equals(getUsername())) {
            return R.error(1, "演示系统不允许修改,完整体验请部署程序");
        }
        String fileName = file.getOriginalFilename();
        fileName = FileUtil.renameToUUID(fileName);
        FileDO sysFile = new FileDO(FileType.fileType(fileName), "/files/" + fileName, new Date());
        try {
            FileUtil.uploadFile(file.getBytes(), bootdoConfig.getUploadPath(), fileName);
        } catch (Exception e) {
            return R.error();
        }

        if (sysFileService.save(sysFile) > 0) {
            return R.ok().put("fileName",sysFile.getUrl());
        }
        return R.error();
    }
}
